#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve() {
  ll p,a,b,c;
  cin>>p>>a>>b>>c;
  ll ans;
  ll at,bt,ct;
  at=p/a*a;
  bt=p/b*b;
  ct=p/c*c;
  if(p%a)at+=a;
  if(p%b)bt+=b;
  if(p%c)ct+=c;
  ans = min({at-p, bt-p, ct-p});
  cout<<ans<<'\n';
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0); cout.tie(0);
  int tc; cin>>tc;
  for(int t = 1; t <= tc; t++) {
    solve();
  }
  return 0;
}
